import * as path from "path";
import * as fs from "fs";
import * as JSON5 from "json5";

// 配置文件路径
let usingConfigurationFilePath: string | undefined = undefined;
const defaultConfigurationFilePath = path.join(
  __dirname,
  "../../config/config.json5",
);
export const configFilePaths = [
  path.join(__dirname, "../../config.json"),
  path.join(__dirname, "../../config.json5"),
  path.join(__dirname, "../../appConfig.json"),
  path.join(__dirname, "../../appConfig.json5"),
  path.join(__dirname, "../../config/config.json"),
  defaultConfigurationFilePath,
  path.join(__dirname, "../../config/appConfig.json"),
  path.join(__dirname, "../../config/appConfig.json5"),
];

// 配置接口
export interface WebsiteConfiguration {
  logo?: string;
  name: string;
  description?: string;
  url: string;
  version?: string;
  copyright?: string;
  setUpTime?: string | Date;
  startRunningTime?: string | Date;
  ICP备案?: string;
  公网安备案?: string;
  萌ICP备案号?: string;
}
export interface EmailConfiguration {
  enable: boolean;
  host: string;
  port: number;
  secure: boolean; // Use `true` for port 465, `false` for all other ports
  user: string;
  pass: string;
}
export interface UserConfiguration {
  // 管理员用户名
  administrators: string[];
  // 站长信息
  master?: {
    nickname?: string;
    username?: string;
    emails?: string[];
  };
}
export interface ArticleConfiguration {
  // 归档数据更新时间间隔（分钟）
  archiveUpdateInterval: number;
  // 点赞功能
  enableLike: boolean;
  // 评论功能
  enableComment: boolean;
  enableCommentReview: boolean;
}
export interface RSSConfiguration {
  enable: boolean;
  // RSS文件更新时间间隔（分钟）
  updateInterval: number;
}
// twikoo 评论系统配置
// 参考 https://twikoo.js.org/frontend.html
export interface TwikooConfiguration {
  enable: boolean;
  envID: string;
  region: "ap-shanghai" | "ap-guangzhou" | "";
  lang: "zh" | "zh-cn" | "zh-hk" | "zh-tw" | "en" | "en-us" | "uz" | "ja";
}
// 百度统计相关配置
export interface BaiduTongjiConfiguration {
  domain: string;
  code: string;
}
// 微信公众号API相关配置
export interface WechatConfiguration {
  appID: string;
  appSecret: string;
}
// 服务相关配置
export interface ServerConfiguration {
  port: number;
  https?: {
    enable: boolean;
    http2: boolean;
    certs?: {
      // 带 default 则 匹配不到时默认使用
      servername: string[];
      cert: string;
      key: string;
    }[];
  };
}
// 内容资源相关
export interface ResourceConfiguration {
  rootDirectoryPath: string;
  articleDirectoryPath: string;
  RSSDirectoryPath: string;
  RSSFilePath: string;
}

export interface Configuration {
  // 网站相关配置
  website: WebsiteConfiguration;
  email: EmailConfiguration;
  user?: UserConfiguration;
  article: ArticleConfiguration;
  rss?: RSSConfiguration;
  // twikoo 评论系统配置
  // 参考 https://twikoo.js.org/frontend.html
  twikoo?: TwikooConfiguration;
  // 统计相关配置
  tongji?: {
    // 百度统计相关配置
    baidu?: BaiduTongjiConfiguration[];
  };
  // 微信公众号API相关配置
  wechat?: WechatConfiguration;
  // 服务相关配置
  server: ServerConfiguration;
  // 内容资源相关
  resource: ResourceConfiguration;
}

// 默认配置
const configuration: Configuration = {
  // 网站相关配置
  website: {
    url: "https://cyue.net",
    version: "0.1",
    logo: "https://cyue.net/logo.png",
    name: "鸽子分享网",
    description: "鸽子分享网",
    copyright: "尘跃",
    setUpTime: "",
    startRunningTime: "",
    ICP备案: "",
    公网安备案: "",
    萌ICP备案号: "",
  },
  email: {
    enable: false,
    host: "",
    port: 465,
    secure: true,
    user: "",
    pass: "",
  },
  user: {
    administrators: [],
    master: {
      nickname: undefined,
      username: undefined,
      emails: [],
    },
  },
  article: {
    // 文章归档更新周期
    archiveUpdateInterval: 60 * 24, // 24小时
    // 点赞功能
    enableLike: true,
    // 评论功能
    enableComment: true,
    enableCommentReview: false,
  },
  rss: {
    enable: true,
    // 更新周期
    updateInterval: 60 * 12, // 12小时
  },
  // twikoo 评论系统配置
  twikoo: {
    enable: false,
    envID: "",
    region: "",
    lang: "zh",
  },
  // 统计相关配置
  tongji: {
    // 百度统计相关配置
    baidu: [],
  },
  // 微信公众号API相关
  wechat: {
    appID: "",
    appSecret: "",
  },

  // 服务相关配置
  server: {
    port: 4433,
    https: {
      enable: false,
      http2: true,
      certs: [],
    },
  },

  // 内容资源相关
  resource: {
    rootDirectoryPath: path.join(__dirname, "../../../cyue-share-resource"),
    articleDirectoryPath: "",
    RSSDirectoryPath: "",
    RSSFilePath: "",
  },
};

// 读取配置文件
export function writeOutConfiguration(
  c: Configuration,
  filePath: string = usingConfigurationFilePath,
): void | never {
  const fileConfiguration = { ...configuration };
  const projectRootPath = path.join(__dirname, "../../");
  for (const index in fileConfiguration.server.https.certs) {
    fileConfiguration.server.https.certs[index].cert = path
      .relative(
        projectRootPath,
        fileConfiguration.server.https.certs[index].cert,
      )
      .replaceAll("\\", "/");
    fileConfiguration.server.https.certs[index].key = path
      .relative(
        projectRootPath,
        fileConfiguration.server.https.certs[index].key,
      )
      .replaceAll("\\", "/");
  }
  for (const key in fileConfiguration.resource) {
    fileConfiguration.resource[key] = path
      .relative(projectRootPath, fileConfiguration.resource[key])
      .replaceAll("\\", "/");
  }
  const configurationString = JSON.stringify(fileConfiguration, null, 2);
  fs.writeFileSync(
    filePath || usingConfigurationFilePath || defaultConfigurationFilePath,
    configurationString,
  );
}
export function loadConfiguration(
  filePaths: string[] = configFilePaths,
): void | never {
  for (const p of filePaths) {
    if (!fs.existsSync(p)) {
      continue;
    }
    usingConfigurationFilePath = p;
    const configurationFile = fs.readFileSync(p, "utf-8");
    const configurationFileJSON: Configuration = JSON5.parse(configurationFile);
    for (const key in configurationFileJSON) {
      // 路径
      if (key === "resource") {
        for (const pKey in configurationFileJSON[key]) {
          configuration[key][pKey] = path.join(
            __dirname,
            "../../",
            configurationFileJSON[key][pKey],
          );
        }
        continue;
      } else if (
        key === "server" &&
        configurationFileJSON[key].https &&
        configurationFileJSON[key].https.certs
      ) {
        Object.assign(configuration[key], configurationFileJSON[key]);
        // https certs 路径处理
        for (const cert of configuration[key].https.certs) {
          if (typeof cert.servername === "string") {
            cert.servername = [cert.servername];
          } else if (!Array.isArray(cert.servername)) {
            cert.servername = undefined;
          }
          cert.cert = path.join(__dirname, "../../", cert.cert);
          cert.key = path.join(__dirname, "../../", cert.key);
        }
        continue;
      }

      Object.assign(configuration[key], configurationFileJSON[key]);
    }
    break;
  }
}
loadConfiguration();

// URL处理
if (!configuration.website.url.slice(0, 5).includes("http"))
  configuration.website.url = `http://${configuration.website.url}`;

// 各类资源文件夹路径
configuration.resource.articleDirectoryPath = path.join(
  configuration.resource.rootDirectoryPath,
  "article",
);
configuration.resource.RSSDirectoryPath = path.join(
  configuration.resource.rootDirectoryPath,
  "rss",
);
configuration.resource.RSSFilePath = path.join(
  configuration.resource.RSSDirectoryPath,
  "rss.xml",
);
console.info("configuration:", configuration);

// 创建文件夹
for (const key in configuration) {
  if (!key.includes("Directory")) continue;
  if (!fs.existsSync(configuration[key]))
    fs.mkdirSync(configuration[key], { recursive: true });
}

export default configuration;
